package com.qiwo.api.controller;

import com.qiwo.api.pojo.dto.UserLoginDTO;
import com.qiwo.api.pojo.vo.TokenVO;
import com.qiwo.api.ucenter.Client;
import com.qiwo.api.ucenter.XMLHelper;
import com.qiwo.common.annotation.Log;
import com.qiwo.common.utils.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.LinkedList;

/**
 * Copyright
 *
 * @author chenwenchao
 * @date 2019/6/6
 * Description:
 */
@Controller
@RequestMapping("/sso")
public class ApiLoginController {

    @GetMapping("/logout")
    public Result<String> logout(){
        Client uc = new Client();

        String $ucsynlogout = uc.uc_user_synlogout();

        System.out.println("退出成功"+$ucsynlogout);

        return Result.ok($ucsynlogout);
    }

    @GetMapping("/login")
    @Log("api登录")
    @ApiOperation("登录")
    public void token(HttpServletResponse response) {

        //Discuz论坛的登录

        Client uc = new Client();

        String $result = uc.uc_user_login("admin", "123456");

        String $ucsynlogin = "";

        LinkedList<String> rs = XMLHelper.uc_unserialize($result);

        if(rs.size()>0){

            int $uid = Integer.parseInt(rs.get(0));

            String $username = rs.get(1);

            String $password = rs.get(2);

            String $email = rs.get(3);

            if($uid > 0) {

                $ucsynlogin = uc.uc_user_synlogin($uid);

            } else if($uid == -1) {

                System.out.println("用户不存在,或者被删除");

            } else if($uid == -2) {

                System.out.println("密码错");

            } else {

                System.out.println("未定义");

            }

            //设置本地Discuz登录的cookie信息，cookie存活时间

            //直接访问论坛就有用户信息了

            try {

                response.setCharacterEncoding("UTF-8");

                //同步Cookie信息

//                response.addHeader("P3P"," CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"");

//              Cookie auth = new Cookie("auth", uc.uc_authcode($password+"\t"+$uid, "ENCODE"));

//              auth.setMaxAge(31536000);

//              //auth.setDomain("localhost");//设置本地cookie

//              response.addCookie(auth);

//              Cookie user = new Cookie("Discuz_loginuser", $username);

//              response.addCookie(user);



                //把返回过来的js文件直接输出在页面上，然后跳转到论坛网站首页就已经是登录之后的

                PrintWriter out = response.getWriter();

                out.write($ucsynlogin);

                out.flush();           } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }else{

            System.out.println("Login failed");

        }

    }
}
